<template>
  <back-dialog-base
    :title="title"
    :visible="visibleViewDialog"
    :hasFooter= false
     @close="clear"
  >
    <template #content>
  <el-tree
      ref="treeRef"
      :data="allPermission"
      show-checkbox
      node-key="name"
      :props="defaultProps"
      @check-change='change'
    >
    </el-tree>
       <span class="dialog-footer">
        <el-button @click="handleClose" type="info">取消</el-button>
        <el-button type="primary" @click="handleOk">确定</el-button>
      </span>
    </template>
  </back-dialog-base>
</template>

<script setup>
import { defineProps, watch, ref, defineEmits } from 'vue'
import BackDialogBase from '@/components/BackDialogBase'
import { permissionList, userPermission, distributionPermission } from '@/api/permission'
import { watchSwitchLang } from '@/utils/i18n'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
const props = defineProps({
  title: {
    type: String,
    default: ''
  },
  visibleViewDialog: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => {}
  }
})
const treeRef = ref(null) //tree
const allPermission = ref([]) //所有权限
const all = ref([])
const i18n = useI18n()
const emits = defineEmits(['onReload'])

// 属性结构配置
const defaultProps = {
  children: 'children',
  label: 'title'
}
// 查询所有的权限
const List = async () => {
  allPermission.value = await permissionList()
  watchSwitchLang(allPermission)
}
List()
// 获取角色的权限
const user = async (id) => {
  const checkedKeys = await userPermission(id)
  if (checkedKeys) treeRef.value.setCheckedKeys(checkedKeys)
}
const change = (data) => {
  const res = treeRef.value.getCheckedNodes()
  const val = []
  res.forEach(element => {
    val.push(element.name)
  })
  all.value = val
}
// 分配权限
const handleOk = async () => {
  await distributionPermission({
    roleId: props.rowData.id,
    permissions: all.value
  })
    ElMessage.success('操作成功')
    handleClose()
}
const handleClose = () => {
   emits('onReload')
}
const clear = () => {
    user(props.rowData.id)
}
watch(
  () => props.rowData || props.rowData.id,
  () => {
    user(props.rowData.id)
  }
)
</script>

<style lang="scss" scoped>
.dialog-footer{
  display: flex;
  justify-content: end;
}
:deep(.el-button--info){
    --el-button-font-color: #9ba7c0;
    --el-button-background-color: rgba(250, 250, 250, 0.39);
    --el-button-border-color: #dedede;
    --el-button-hover-color: rgba(250, 250, 250, 0.41);
    --el-button-active-font-color: #9ba7c0;
    --el-button-active-background-color: rgba(250, 250, 250, 0.41);
    --el-button-active-border-color: #dedede;
}
</style>
